/**
 * Created by DukeCrushIt on 2015/7/31.
 */
class PetMgr{
    private petContainer:egret.DisplayObjectContainer;
    public curPet:Pet;
    public bagPostion:egret.Point = null;
    public bagPostion1:egret.Point = null;
    public pets:Pet[];//所有饲养中的宠物
    private curClickTimes:number=0;
    public curIndatePetId:number = 0;
    public static tickNum:number = 0;
    public static checkGap:number = 0;
    public floor:egret.Bitmap;
    public static interval;
    public excludeArea:egret.Rectangle;
    public startTouchTime:number;
    public constructor(){
        this.init();
    }
    private init(){
        this.pets = [];
    }
    private started:boolean = false;
    public start(){
        if( !this.started ){
            window["__startWS"]();
            PetMgr.interval = setInterval(this.onTimer, 1000);
            PerformanceMonitor.getInstance().start();
            this.started = true;
            this.floor = new egret.Bitmap();
            this.floor.texture = RES.getRes("img_floor_jpg");
            this.floor.touchEnabled = false;
            this.floor.cacheAsBitmap = true;
            this.floor.y = GameConst.StageH - this.floor.height;
            GameConst.Stage.addChildAt(this.floor,0);
            SoundMgr.getInstance().playBg();
            window["__iwars"](0);
            window["__activeList"]();
            window["__vips"]();
        }
    }

    public changeBg(type:number){
        if( type == 0){
            this.floor.texture = RES.getRes("img_floor_jpg");
        }else{
            RES.getResByUrl(GameConst.Res_Root+"resource/assets/decorates/"+type+"-2.jpg",this.onBgComplete,this);
        }
        var url = GameConst.Res_Root+"/resource/assets/decorates/"+type+"-1.jpg";
        RES.getResByUrl(url,this.onBgComplete1,this);
    }

    private onBgComplete(hehe:any){
        this.floor.texture = hehe;
    }

    private onBgComplete1(hehe:any){
        DisplayController.instance().bg.texture = hehe;
    }

    private onTimer() {
        PetMgr.tickNum++;
        PetMgr.checkGap++;
        var cnt:number;
        if( SceneMgr.getInstance().currentScene==SceneMgr.SCENE_MAIN){
            PetMgr.getInstance().autoHair(-1);
        }

        if (PetMgr.checkGap >= 5) {//5秒检查收毛和点击
            var obj:Object = Model.clickData;
            for (var key in obj) {
                cnt = Model.clickData[key];
                if (cnt != 0) {
                    window["__click"](parseInt(key), cnt);
                }
            }
            Model.clickData = {};

            PetMgr.checkGap = 0;
            SoundMgr.getInstance().checkUnfinishedEffects();
        }

        //Model.produceHairData = {};
        if (PetMgr.tickNum == 120) {//每分钟自动同步PetMgr.tickNum == 60 ||
            PetMgr.tickNum = 0;
            window["__heartbeat"]();
            obj = Model.produceHairData;
            for (key in obj) {
                cnt = Model.produceHairData[key];
                if (cnt != 0) {
                    window["__glean"](parseInt(key), cnt,1);
                }
            }
        }
    }

    public autoHair(amount:number,needRecord:boolean=true){
        if( amount == 0) return;
        var autoHairPer = this.curPet.getHair();
        if( amount == -1){
            amount = autoHairPer;//this.curPet.autoHairPer;
        }
        var halfH:number = GameConst.StageH >> 1;
        var targetX;
        if( amount <= autoHairPer){
            hair = PetMgr.produce();
            hair.x = 0;
            hair.y = halfH + 75 + 90*(1 + Math.random());
            hair.value = amount;
            hair.setType(this.curPet.petId);
            hair.sameType = this.curPet.type == Model.me.myType;
            hair.needRecord = needRecord;
            this.addHair(hair);
            item = MoveMgr.produce();
            targetX = 240+480*(0.5-Math.random());
            if( targetX >= 240){
                hair.x = 480;
            }
            if(this.excludeArea && this.excludeArea.contains(targetX,hair.y)){
                targetX = this.excludeArea.left-10;
            }
            item.init(hair,targetX,hair.y,600,null,null,true);
            MoveMgr.getInstance().addItem(item);
            return;
        }
        var times = amount/(2*autoHairPer) >> 0;
        times =  times <= 25 ? times : 25;
        var avg:number = Math.floor(amount/(times*2));
        var hair:Hair;
        var item:MoveItem;
        while(times > 0 && amount > 0){
            hair = PetMgr.produce();
            hair.setType(this.curPet.petId);

            hair.x = 0;
            hair.y = halfH + 75 + 90*(1 + Math.random());
            hair.needRecord = needRecord;
            if( amount >= avg ){
                hair.value = avg;
                amount -= avg;
            }else{
                hair.value = amount;
                amount = 0;
            }
            this.addHair(hair);
            targetX = 240*(1-Math.random());
            if(this.excludeArea && this.excludeArea.contains(targetX,hair.y)){
                targetX = this.excludeArea.left-10;
            }
            hair.sameType = this.curPet.type == Model.me.myType;
            item = MoveMgr.produce();
            item.init(hair,targetX,hair.y,600,null,null,true);
            MoveMgr.getInstance().addItem(item);

            if( amount <= 0) break;

            hair = PetMgr.produce();
            hair.setType(this.curPet.petId);

            hair.needRecord = needRecord;
            hair.x = GameConst.StageW;
            hair.y = halfH + 75 + 90*(1 + Math.random());
            hair.sameType = this.curPet.type == Model.me.myType;
            this.addHair(hair);
            if( amount >= avg ){
                hair.value = avg;
                amount -= avg;
            }else{
                hair.value = amount;
                amount = 0;
            }
            targetX = 240*(1+Math.random());
            if(this.excludeArea && this.excludeArea.contains(targetX,hair.y)){
                targetX = this.excludeArea.left-10;
            }
            item = MoveMgr.produce();
            item.init(hair,targetX,hair.y,600,null,null,true);//fixme can not cover bag button
            MoveMgr.getInstance().addItem(item);
            times--;
        }
    }

    private touchBeginTime:number;
    private isStartedByPet:boolean;
    private inScale:boolean = false;
    private onTouchBegin(evt:egret.TouchEvent){
        //evt.stopImmediatePropagation();
        this.touchBeginTime = egret.getTimer();
        DisplayController.instance().stage.addEventListener(egret.TouchEvent.TOUCH_MOVE,this.onTouchMove, this);
        DisplayController.instance().stage.addEventListener(egret.TouchEvent.TOUCH_END,this.onTouchEnd, this);
        this.petContainer.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchTap, this);
        this.isStartedByPet = evt.target != null && evt.target.name == "pet";
        if(evt.target != undefined && evt.target.name == "pet"){
            evt.target.scaleX = evt.target.scaleY = 0.95;
            this.inScale = true;
        }
    }
    private ohShit(evt:egret.TouchEvent){
        if(evt.target.name == "shit"){
            this.sweeping = true;
            window["__dateSweep"](this.record.record.id);
        }
    }
    private sweeping:boolean;
    private onTouchTap(evt:egret.TouchEvent){
        Model.GLEAN_NOW = false;
        if( evt.target.name == "pet" && SceneMgr.getInstance().currentScene == SceneMgr.SCENE_MAIN){//only in mainscene can produce hairs
            SoundMgr.getInstance().playEffect(SoundMgr.HAIR);
            if( this.curPet.clickHairCdTime > Model.SYSTIME) return;//冷却中
            //if( this.curPet.clickTimes + this.curClickTimes>= 120 ) return;//取消点击次数
            Model.updateClickCnt(this.curPet.petId,1);
            //window["__click"](this.curPet.petId, 1);//fixme
            var hairCnt:number = Math.ceil(Math.random()*3);
            var total:number = this.curPet.clickHairPer;
            var avg:number = Math.ceil(total/hairCnt);
            var fur:Hair;
            var item:GravityItem;
            var halfH:number = GameConst.StageH >> 1;
            while(hairCnt > 0 && total > 0){
                fur = PetMgr.produce();
                fur.setType(this.curPet.petId);
                fur.x = evt.stageX;
                fur.y = evt.stageY;
                if( hairCnt != 1){
                    fur.value = avg;
                    total -= avg;
                }else{
                    fur.value = total;
                    total = 0;
                }
                fur.sameType = this.curPet.type == Model.me.myType;

               this.addHair(fur);
                item = GravitySystem.produce();
                item.displayObject = fur;
                item.currentSpeedX = (Math.random()-0.5)*20;
                item.currentSpeedY = -10*(1+Math.random());
                item.targetY =halfH + 75 + 90*(1 + Math.random());
                GravitySystem.getInstance().addItem(item);
            }
            this.curClickTimes++;
        }else{
            var len:number = this.hairs.length;
            var hair:Hair;;
            while(len>0){
                hair = this.hairs[len-1];
                if( !GravitySystem.getInstance().contains(hair.name) && !hair.isRemoving && GetDistance(hair.x,hair.y,evt.stageX,evt.stageY) <= 60){
                    hair.source = 0;
                    this.gatherHair(hair);
                }else if( hair.isRemoving && Model.SYSTIME - hair.removeReferTime >3000){
                    this.gatherHair(hair);
                }
                len--;
            }
        }
        if( !Model.GuideStarted )
            evt.stopImmediatePropagation();//fixme guide use
    }

    public onPropUseBack(hairData:any){
        if( hairData.type == this.curPet.type){
            var myHair:number = hairData.type == Model.GOOD_TYPE_CAT ? Model.me.catHair : Model.me.dogHair;
            var gain:number = hairData.hair - myHair;
            var avg:number = Math.floor(gain/6);
            avg = avg <= 0 ? 1 : avg;
            while( gain > 0){
                var hair:Hair = PetMgr.produce();
                hair.needRecord = false;
                hair.x = (GameConst.StageW >> 1) + (0.5-Math.random())*10;
                hair.y = (GameConst.StageH >> 1) + (Math.random() - 0.5)*20;
                hair.value = gain > avg ? avg : gain;
                hair.setType(this.curPet.petId);
                gain -= hair.value;
                this.petContainer.addChild(hair);
                this.gatherHair(hair);
            }
        }else{
            if( hairData.type == Model.GOOD_TYPE_CAT){
                Model.me.catHair = hairData.hair;
            }else if( hairData.type == Model.GOOD_TYPE_DOG){
                Model.me.dogHair = hairData.hair;
            }
        }
    }

    public onSweepBack(cnt:number){
        if( this.shit != null && this.shit.parent){
            this.petContainer.removeChild(this.shit);
            this.shit.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.ohShit, this);
        }
        this.sweeping = false;
        //var avg:number = Math.floor(cnt/this.curPet.autoHairPer);
        //avg = avg <= 0 ? 1 : avg;
        //while( cnt > 0){
        //    var hair:Hair = PetMgr.produce();
        //    hair.needRecord = false;
        //    hair.x = GameConst.StageW >> 1;
        //    hair.y = (GameConst.StageH >> 1) - 20;
        //    hair.value = cnt > avg ? avg : cnt;
        //    cnt -= hair.value;
        //    this.petContainer.addChild(hair);
        //    this.gatherHair(hair);
        //}
        //if( PlayBar.getInstance().parent != null)
        //    PlayBar.getInstance().updateHairNum();
        //DiamondElement.getInstance().updateDisplay();
    }
    /**
     * type 0 正常收毛
     * type 1 溢出收毛（120秒同步）
     * */
    private gatherHair(hair:Hair,type:number=0){
        if( hair.source == 1){
            Model.STOREHAIRS+=hair.value;
            Model.GLEAN_NOW = true;//fixme
        }
        else{
            if( type == 0){
                if(hair.needRecord)
                    window["__glean"](this.curPet.petId,hair.value,0);
            }else{
                if(hair.needRecord){
                    Model.updateProduceHairData(this.curPet.petId,hair.value);
                    DiamondElement.getInstance().updateDisplay();
                }
            }

        }
        this.startTouchTime = Model.SYSTIME;
        var idx = this.hairs.indexOf(hair);
        if( idx != -1)
            this.hairs.splice(idx,1);

        if( PerformanceMonitor.getInstance().getSwithState(PerformanceMonitor.EFFECTS)){
            hair.removeSelf();
        }else{
            hair.jump();
            if(this.hairs.length == 0){
                EffectMgr.getInstance().playEffect("floor0",1);
                EffectMgr.getInstance().playEffect("floor1",1);
                EffectMgr.getInstance().playEffect("floor2",1);
                EffectMgr.getInstance().playEffect("floor3",1);
            }
        }
    }
    private effectPlayed:boolean = false;
    private inPet:boolean;
    private onTouchMove(evt:egret.TouchEvent){
        var len:number = this.hairs.length;
        var hair:Hair;
        var needStop:boolean =false;
        if(!this.effectPlayed){
            SoundMgr.getInstance().playEffect(SoundMgr.TOUCHMOVE);
            this.effectPlayed = true;
        }
        while(len>0){
            hair = this.hairs[len-1]
            if( !GravitySystem.getInstance().contains(hair.name) && !hair.isRemoving && GetDistance(hair.x,hair.y,evt.localX-this.petContainer.x,evt.localY-this.petContainer.y) <= 60){
                hair.source = 1;
                this.gatherHair(hair);
                needStop = true;
            }else if( hair.isRemoving && Model.SYSTIME - hair.removeReferTime >3000){
                this.gatherHair(hair);
                needStop = true;
            }
            len--;
        }
        if( evt.target == null || (evt.target.name == "pet" && this.inPet) ){
            return;
        }else if( evt.target.name != "pet"){
            this.inPet = false;
            return;
        }

        if( this.curPet.mood >= this.curPet.maxMood ) return;
        if(this.fondleCdTime + Model.ONE_MINUTES < Model.SYSTIME){
        //if( (!this.isStartedByPet || egret.getTimer() - this.touchBeginTime > 300)){//this.curPet.fondleMood < this.curPet.fondleMaxMood &&
            window["__fondle"](this.curPet.petId);
            AnimationController.getInstance().gotoAndPlay("mypet",AnimationController.FUMO_ANIMATION,1);
            this.inPet = true;
            needStop = true;
        }
        if( needStop && !Model.GuideStarted )
            evt.stopImmediatePropagation();//FIXME guide use
    }
    private onTouchEnd(evt:egret.TouchEvent){
        DisplayController.instance().stage.removeEventListener(egret.TouchEvent.TOUCH_MOVE,this.onTouchMove, this);
        DisplayController.instance().stage.removeEventListener(egret.TouchEvent.TOUCH_END,this.onTouchEnd, this);

        if( Model.GLEAN_NOW  && Model.STOREHAIRS > 0){
            window["__glean"](PetMgr.getInstance().curPet.petId,Model.STOREHAIRS,0);
            Model.STOREHAIRS = 0;
            Model.GLEAN_NOW = false;
        }

        this.inPet = false;
        this.effectPlayed = false;
        if( this.inScale && this.curArmature.display ){
            this.curArmature.display.scaleX = this.curArmature.display.scaleY = 1;
        }
        if( !Model.GuideStarted )
            evt.stopImmediatePropagation();
    }

    public initContainer(petContainer:egret.DisplayObjectContainer){
        this.petContainer = petContainer;
        petContainer.touchEnabled = true;
    }
    public getTotalHairs():number{
        var len = this.pets.length;
        var pet:Pet;
        var result = 0;
        for(var idx = 0 ; idx < len; idx++){
            pet = this.pets[idx];
            result += pet.getHair();
        }
        return result;
    }
    public checkGuildPetCnt(){
        var len = Model.pets.length;
        var pet:Pet;
        var petdata:GoodInfo;
        for(var i = 0; i < len; i++){
            pet = Model.pets[i];
            petdata = Model.getPetInfoById(pet.petId);
            if( petdata.classify == 12){
                if( pet.type == Model.GOOD_TYPE_CAT){
                    Model.GuildCatCnt++;
                } else if( pet.type == Model.GOOD_TYPE_DOG){
                    Model.GuildDogCnt++;
                }
            }
        }
    }
    public ownPetCnt = 0;
    public addPet(pet:Pet){
        if( pet.rear)
            this.pets.push(pet);
        if( pet.inDate )
            this.curIndatePetId = pet.petId;
        if( this.curPet == undefined ){
            this.curPet = pet;
        }
    }

    public delPet(pet:Pet,index:number=-1){
        if( index != -1){
            this.pets.splice(index, 1);
        }
    }

    public getPetIndexById(petid:number):number{
        var result = -1;
        var len = this.pets.length;
        var pet:Pet;
        for(var idx = 0; idx < len; idx++){
            pet = this.pets[idx];
            if( pet.petId == petid){
                result = idx;
                break;
            }
        }
        return result;
    }

    public othersPet:Pet;//他人的宠物
    public record:any;
    private shit:egret.Bitmap;
    private tempArmature:dragonBones.Armature;
    public showOthersPet(record:any = null){
        if( record == null){
            record = this.record;
        }else{
            this.record = record;
        }

        var groupname = this.othersPet.petId+"_"+0;
        if( !RES.isGroupLoaded(groupname) ){
            if( RES.getGroupByName(groupname).length == 0)
                RES.createGroup(groupname,[groupname+"_texture_json",groupname+"_texture_png",groupname+"_json"],true);
            DragonLoader.getInstance().loadgroup(groupname,this, this.showOthersPet);
            return;
        }

        var currentScene = SceneMgr.getInstance().currentScene;
        if( currentScene != SceneMgr.SCENE_OTHERS && currentScene != SceneMgr.SCENE_GETOUT) return;

        if( this.tempArmature != null && this.tempArmature.display != null && this.tempArmature.display.parent != null){
            this.tempArmature.display.parent.removeChild(this.tempArmature.display);
            AnimationController.getInstance().uncontroll("others");
            dragonBones.WorldClock.clock.remove(this.tempArmature);
            this.tempArmature = null;
        }
        this.tempArmature = DragonLoader.getInstance().dragonBonesFac.buildArmature("armatureName",groupname);
        this.tempArmature.display.touchEnabled = true;
        this.tempArmature.display.touchChildren = false;
        this.tempArmature.display.name = "pet";
        this.tempArmature.display.y = (GameConst.StageH >> 1) + 150;
        AnimationController.getInstance().control("others",this.tempArmature);
        this.tempArmature.display.x = (GameConst.StageW >> 1) + (this.curSceneType == 1 ? 80 : 0);
        AnimationController.getInstance().gotoAndPlay("others",AnimationController.NORMAL_ANIMATIONS[4],1,true);
        this.petContainer.addChildAt(this.tempArmature.display,0);

        if(record != null && record.record != null  ){
            this.autoHair(record.record.hair,false);//打架完掉毛
            if( !PerformanceMonitor.getInstance().getSwithState(PerformanceMonitor.EFFECTS)){
                if( record.record.result == 0){
                    EffectMgr.getInstance().playEffect("mood",3,0,this,this.autoGatherAll);
                }else if( record.record.result == 1){
                    EffectMgr.getInstance().playEffect("fight",3,0,this,this.autoGatherAll);
                }
            }else{
                setTimeout(function(){
                    arguments[1].call(arguments[0]);
                },1000,this,this.autoGatherAll);
            }
            if( record.record.withShit ){
                if( this.shit == null)
                    this.shit = new egret.Bitmap(RES.getRes("shit"));
                this.shit.x = GameConst.StageW*0.6;
                this.shit.y = GameConst.StageH * 0.8;
                this.shit.name = "shit";
                this.shit.touchEnabled = true;
                this.shit.addEventListener(egret.TouchEvent.TOUCH_TAP, this.ohShit, this);
                this.petContainer.addChild(this.shit);
            }
        }
    }

    private autoGatherAll(){
        var child:any;
        var hairs = 0;
        while(this.petContainer.numChildren){
            this.curSceneType = 0;
            child = this.petContainer.removeChildAt(0);
            if( child instanceof Hair){
                //this.gatherHair(child);
                PetMgr.reclaim(child);
                hairs+=child.value;
            }else if( child == this.shit){
                if( !this.sweeping ){
                    this.sweeping = false;
                    //window["__dateSweep"](this.record.record.id);
                }
            }
        }
        window["__glean"](this.record.pet.petId,hairs,0);

        this.updatePet(this.record.pet);
        Model.inDating = false;
        if( this.record.record.result == 0){
            RemindPanel.getInstance().showContent("玩的真开心呀！本次共收获"+this.record.record.hair+"个毛",this,this.onGatherAllComplete,this.onGatherAllComplete);
        }else{
            if( this.record.record.winnerId == Model.me.id){
                RemindPanel.getInstance().showContent("哼，还有谁！本次共收获"+this.record.record.hair+"个毛",this,this.onGatherAllComplete,this.onGatherAllComplete);
            }else{
                RemindPanel.getInstance().showContent("可恶，一定是草皮太滑了！本次共收获"+this.record.record.hair+"个毛",this,this.onGatherAllComplete,this.onGatherAllComplete);
            }
        }
        Model.checkGuide("date_complete");
        //EffectMgr.getInstance().playEffect("mood",1);
    }
    public onGatherAllComplete(){

        SceneMgr.getInstance().switchScene(SceneMgr.SCENE_GETOUT);
        Model.checkGuide("dated");
    }

    private curSceneType;
    public showMain(type:number=0){
        if( type == 0){
            if( !PetMgr.interval){
                PetMgr.interval = setInterval(this.onTimer, 1000);
            }
            var autoGap = Math.floor((Model.SYSTIME - this.curPet.lastAutoTime)/1000) * this.curPet.autoHairPer;
            var len:number = this.hairs.length;
            var hair:Hair;
            for(var i = 0; i < len ; i++){
                hair = this.hairs[i];
                this.petContainer.addChild(hair);
                autoGap -= hair.value;
            }
            DisplayController.instance().stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTouchBegin,this);
            if( autoGap + this.curPet.hair > 0){//fixme 草泥马 这个要怎么做
                this.autoHair(autoGap+this.curPet.hair);
            }
        }
        this.updatePetDisplay(type);
        this.curSceneType = type;
    }
    public onChangeReer(data:any){
        var petid = data.petId;
        Model.updatePetData(data);
        var index = this.getPetIndexById(petid);
        if( data.rear && index == -1){
            this.addPet(Model.getPetById(petid));
        }else if( !data.rear && index != -1 ){
            this.delPet(null,index);
            if( this.curPet.petId == petid){
               this.curPet = this.pets[0];
                PlayBar.getInstance().setPage(0);
            }
        }
    }
    public updatePet(data:any){
        var petid:number = data.petId;//todo 要处理非饲养状态的情况
        if( data.inDate){
            this.curIndatePetId = data.petId;
        }
        if( this.curPet.petId == petid){
            this.curPet.initFromData(data);
            this.fondleCdTime = BuffMgr.getInstance().getFondleTime(this.curPet.petId);
            this.curClickTimes = 0;
            if( PlayBar.getInstance().parent != null)
                PlayBar.getInstance().updateMood();
        }else {
            Model.updatePetData(data);
        }
    }

    public cleanMain(){
        dragonBones.WorldClock.clock.remove(this.curArmature);
        if( this.tempArmature != null){
            dragonBones.WorldClock.clock.remove(this.tempArmature);
            if( this.tempArmature.display != null && this.tempArmature.display.parent != null){
                this.tempArmature.display.parent.removeChild(this.tempArmature.display);
            }
            this.tempArmature.dispose();
            AnimationController.getInstance().uncontroll("others");
            this.tempArmature = null;
        }
        while(this.petContainer.numChildren > 0){
            this.petContainer.removeChildAt(0);
        }
        DisplayController.instance().stage.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTouchBegin,this);
        DisplayController.instance().stage.removeEventListener(egret.TouchEvent.TOUCH_MOVE,this.onTouchMove, this);
        DisplayController.instance().stage.removeEventListener(egret.TouchEvent.TOUCH_END,this.onTouchEnd, this);
        this.petContainer.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchTap, this);
        FrameMgr.getInstance().delController(AnimationController.getInstance().name);
        this.record = null;
        //if( PetMgr.interval){
        //    clearInterval(PetMgr.interval);
        //    PetMgr.interval = 0;
        //}
        if( SceneMgr.getInstance().currentScene == SceneMgr.SCENE_MAIN){
            var obj = Model.produceHairData;
            for (var key in obj) {
                var cnt = Model.produceHairData[key];
                if (cnt != 0) {
                    window["__glean"](parseInt(key), cnt,1);
                }
            }
        }
    }

    private hairs:Hair[] = [];
    public addHair(hair:Hair){
        this.petContainer.addChild(hair);
        this.hairs.push(hair);
        var hair:Hair;
        while( this.hairs.length >= 50){
            hair= this.hairs.shift();
            hair.source = 0;
            this.gatherHair(hair,1);
        }
    }

    private curArmature:dragonBones.Armature;
    private curArmatureName:string;
    public updatePetDisplay(type:number=0){
        if( this.curArmature != null ){
            if( this.curArmature.display != null && this.curArmature.display.parent != null){
                this.curArmature.display.parent.removeChild(this.curArmature.display);
            }
            this.curArmature.dispose();
            AnimationController.getInstance().uncontroll("mypet");
            dragonBones.WorldClock.clock.remove(this.curArmature);
            this.curArmature = null;
        }

        if(type != 1){
            var groupname = this.curPet.petId+"_"+0;
        }else{
            groupname = this.curIndatePetId+"_"+0;
        }

        if( !RES.isGroupLoaded(groupname) ){
            if(RES.getGroupByName(groupname).length == 0)
                RES.createGroup(groupname,[groupname+"_texture_json",groupname+"_texture_png",groupname+"_json"],true);
            DragonLoader.getInstance().loadgroup(groupname,this, this.updatePetDisplay,type);
            return;
        }
        if(RES.isGroupLoaded(groupname)){
            if( this.curArmature == null){
                this.curArmature = DragonLoader.getInstance().dragonBonesFac.buildArmature("armatureName",groupname);
                this.curArmature.display.touchEnabled = true;
                this.curArmature.display.touchChildren = false;
                this.curArmature.display.name = "pet";
                this.curArmature.display.y = (GameConst.StageH >> 1) + 150;
                AnimationController.getInstance().control("mypet",this.curArmature);
                this.curArmatureName = groupname;
            }
            if( type == 0 || type == 2){
                this.curArmature.display.x = GameConst.StageW >> 1;
            }else{
                this.curArmature.display.x = (GameConst.StageW >> 1) - 80;
            }
            dragonBones.WorldClock.clock.add(this.curArmature);
            AnimationController.getInstance().gotoAndPlay("mypet",AnimationController.NORMAL_ANIMATIONS[4],1,true);
            FrameMgr.getInstance().addControll(AnimationController.getInstance().frameItem);
            this.petContainer.addChildAt(this.curArmature.display,0);
        }else{
            DragonLoader.getInstance().loadgroup(groupname,this, this.updatePetDisplay);
        }

    }

    public onPropBack(propId){
        if( this.curArmature.animation.hasAnimation(propId.toString())){
            AnimationController.getInstance().gotoAndPlay("mypet",propId.toString(),1);
        }
    }

    private onResourceLoadComplete(event:RES.ResourceEvent):void {
        if( event.groupName == this.curPet.petId.toString()){
            this.updatePetDisplay(0);
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
        }
    }
    private savedHairMap = {};
    private fondleCdTime:number = 0;
    public selectPetByIndex(idx:number){
        if( idx >= this.pets.length) return;
        var targetPet = this.pets[idx];
        if(this.curPet == targetPet) return;
        var lastPet = this.curPet.petId;
        this.curPet = targetPet;
        this.fondleCdTime = BuffMgr.getInstance().getFondleTime(this.curPet.petId);
        if( this.curSceneType == 0){
            var hair:Hair;
            GravitySystem.getInstance().removeAllHairItem();
            MoveMgr.getInstance().removeAllHairItems();

            while( this.hairs.length != 0){
                hair = this.hairs.pop();
                if( this.petContainer.contains(hair))
                    this.petContainer.removeChild(hair);
                if(!this.savedHairMap[lastPet]){
                    this.savedHairMap[lastPet] = [];
                }
                this.savedHairMap[lastPet].push([hair.type,hair.value,hair.x,hair.y,hair.sameType]);
                PetMgr.reclaim(hair);

            }
            if(this.savedHairMap[this.curPet.petId]){
                var data;
                while(this.savedHairMap[this.curPet.petId].length){
                    data = this.savedHairMap[this.curPet.petId].pop();
                    hair = PetMgr.produce();
                    hair.value = data[1];
                    hair.x = data[2];
                    hair.y = data[3];
                    hair.sameType = data[4];
                    hair.setType(data[0]);
                    this.addHair(hair);
                }
            }
            var autoGap = Math.floor((Model.SYSTIME - targetPet.lastAutoTime)/1000) * targetPet.autoHairPer;
            if( autoGap + this.curPet.hair != 0)
                this.autoHair(this.curPet.hair+autoGap);
        }

        this.updatePetDisplay(this.curSceneType);
        if( PlayBar.getInstance().parent != null){
            PlayBar.getInstance().updateDisplay();
        }
    }

    public initBagPosition(point:egret.Point, point1:egret.Point){
        this.bagPostion = this.petContainer.globalToLocal(point.x+30,point.y+20);
        this.bagPostion1 = this.petContainer.globalToLocal(point1.x+30,point1.y+20);
    }

    private static _itemCache:Hair[] = [];
    public static produce():Hair{
        if( PetMgr._itemCache.length != 0)
            return PetMgr._itemCache.shift();
        return new Hair();
    }
    public static reclaim(item:Hair){
        if( GravitySystem.getInstance().contains(item.name)){
            GravitySystem.getInstance().removeItemByName(item.name);
        }
        if( PetMgr._itemCache.indexOf(item) == -1)
            PetMgr._itemCache.push(item);
    }

    private static _instance:PetMgr;
    public static getInstance():PetMgr{
        if( PetMgr._instance == null )
            PetMgr._instance = new PetMgr();
        return PetMgr._instance;
    }
}